/*
 * Copyright (c) 2006, 2022, webrx.cn All rights reserved.
 *
 */
package cn.webrx;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * <p>Project: javase2203 - T18
 * <p>Powered by webrx On 2022-08-10 10:02:01
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 17
 */
public class T18 {
    //定义semaphore实例，设置许可数为10，即停车位为2个
    Semaphore semaphore = new Semaphore(2);

    void stop() {
        String t = Thread.currentThread().getName();
        try {
            System.out.println(t + "：尝试进入停车场...");
            //尝试获取许可，如果没有，则等待
            semaphore.acquire();
            //模拟停车
            long time = (long) (Math.random() * 50 + 10);
            System.out.println(t + "：进入了停车场，停车" + time + "秒...");
            TimeUnit.SECONDS.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println(t + "：开始驶离停车场...");
            //释放许可
            semaphore.release();
            System.out.println(t + "：离开了停车场！");
        }
    }

    public static void main(String[] args) {
        T18 t = new T18();
        new Thread(t::stop,"预A-SY281").start();
        new Thread(t::stop,"预A-6632A").start();
        new Thread(t::stop,"预B-SY888").start();
        new Thread(t::stop,"预C-58FH6").start();
        new Thread(t::stop,"预D-SH283").start();
        new Thread(t::stop,"预K-AB381").start();
    }
}
